<template>
    <div>
        <div style="padding: 10px;" class="test">
            <!--            分页栏-->
            <div style="margin: 10px 0;">

                <el-form label-width="80px" size="small" style="margin:0 40px;" :rules="rules" :model="form">
                    <el-form-item label="试卷ID" style="display: none">
                        <el-input v-model="form.paperId" style="width: 205px;" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="试卷名称">
                        <el-input v-model="form.paperName" style="width: 205px;" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="课程名称">
                        <el-select clearable filterable v-model="form.courseId" placeholder="请选择" @change="getQuestionCount">
                            <el-option v-for="item in course" :key="item.courseId" :label="item.courseName"
                                       :value="item.courseId"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="组卷类型">
                        <el-select v-model="form.makePaperMethod" placeholder="请选择"
                                   @change="changeMakePaperMethodHandle">
                            <el-option v-for="item in makePaperMethod" :key="item.id" :label="item.value"
                                       :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <!--添加试卷信息-->
                    <el-form-item label="添加题目" v-if="form['makePaperMethod'] == 1">
                        <el-button type="primary" style="margin-left: 20px;" @click="addQuestion">添加题目</el-button>
                    </el-form-item>

                    <el-form-item label="组卷信息" :key="key" v-show="form['makePaperMethod'] == 2">
                        <el-card class="box-card">
                            <div slot="header" class="clearfix">
                                <span style="float: right;height: 20px;line-height: 20px;color: red;font-size: 14px;font-weight: bold;">试卷总分：{{paperScore}}分</span>
                            </div>
                            <el-descriptions direction="vertical"  :column="6" border>
                                <el-descriptions-item label="单选题数量">
                                   <div style="display: inline-block;">
                                       <el-input-number style="display: inline-block;" v-model="form.radioQuestionCount" controls-position="right"  :min="0" :max="questionCounts[1]"></el-input-number>
                                       <span style="font-size: 14px;margin-left: 5px;" >/{{ questionCounts[1] }}</span>
                                   </div>
                                </el-descriptions-item>
                                <el-descriptions-item label="单选题分数">
                                    <el-input-number style="display: inline-block;" v-model="form.radioScore" controls-position="right"  :min="0" ></el-input-number>
                                </el-descriptions-item>
                                <el-descriptions-item label="多选题数量">
                                    <div style="display: inline-block;">
                                        <el-input-number style="display: inline-block;" v-model="form.checkboxQuestionCount" controls-position="right"  :min="0" :max="questionCounts[2]"></el-input-number>
                                        <span style="font-size: 14px;margin-left: 5px;">/{{questionCounts[2]}}</span>
                                    </div>
                                </el-descriptions-item>
                                <el-descriptions-item label="多选题分数">
                                    <el-input-number style="display: inline-block;" v-model="form.checkboxScore" controls-position="right"  :min="0" ></el-input-number>
                                </el-descriptions-item>
                                <el-descriptions-item label="判断题数量">
                                    <div style="display: inline-block;">
                                        <el-input-number style="display: inline-block;" v-model="form.judgeQuestionCount" controls-position="right"  :min="0" :max="questionCounts[3]"></el-input-number>
                                        <span style="font-size: 14px;margin-left: 5px;">/{{questionCounts[3]}}</span>
                                    </div>
                                </el-descriptions-item>
                                <el-descriptions-item label="判断题分数">
                                    <el-input-number style="display: inline-block;" v-model="form.judgeScore" controls-position="right"  :min="0" ></el-input-number>
                                </el-descriptions-item>
                            </el-descriptions>

                        </el-card>
                    </el-form-item>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <div class="grid-content bg-purple">
                                <el-form-item label-width="100px" label="单选题数量">
                                    <el-input-number v-model="form.radioQuestionCount" :precision="0" :step="1" :min="0"
                                                     :max="100"></el-input-number>
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content bg-purple">
                                <el-form-item label-width="100px" label="多选题数量">
                                    <el-input-number v-model="form.checkboxQuestionCount" :precision="0" :step="1"
                                                     :min="0"
                                                     :max="100"></el-input-number>
                                </el-form-item>
                            </div>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <div class="grid-content bg-purple">
                                <el-form-item label-width="100px" label="判断题数量">
                                    <el-input-number v-model="form.judgeQuestionCount" :precision="0" :step="1"
                                                     :min="0"
                                                     :max="100"></el-input-number>
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content bg-purple">
                                <el-form-item label-width="100px" label="填空题数量">
                                    <el-input-number v-model="form.fillQuestionCount" :precision="0" :step="1" :min="0"
                                                     :max="100"></el-input-number>
                                </el-form-item>
                            </div>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <div class="grid-content bg-purple">
                                <el-form-item label-width="100px" label="客观题数量">
                                    <el-input-number v-model="form.objectiveQuestionCount" :precision="0" :step="1"
                                                     :min="0"
                                                     :max="100"></el-input-number>
                                </el-form-item>
                            </div>
                        </el-col>
                    </el-row>
                    <el-form-item label="单选题">
                        <el-card class="box-card">
                            <div v-for="(question,index) in form.questionList" :key="index">
                                <div v-if="question.questionType == 1">
                                    <el-form-item :label="`题目：`">
                                        <el-row :gutter="20">
                                            <el-col :span="20">
                                                <div class="grid-content bg-purple"
                                                     v-html="question.questionTitle"></div>
                                                <div class="answer">
                                                    <span>A. {{question.optionA}}</span>
                                                    <span>B. {{question.optionB}}</span>
                                                    <span>C. {{question.optionC}}</span>
                                                    <span>D. {{question.optionD}}</span>
                                                </div>
                                            </el-col>
                                            <el-col :span="1">
                                                <div class="grid-content bg-purple">
                                                    <el-button type="text" @click="deleteQuestion(index)">删除
                                                    </el-button>
                                                </div>
                                            </el-col>
                                        </el-row>
                                    </el-form-item>
                                </div>
                            </div>
                        </el-card>
                    </el-form-item>
                    <el-form-item label="多选题">
                        <el-card class="box-card">
                            <div v-for="(question,index) in form.questionList" :key="index">
                                <div v-if="question.questionType == 2">
                                    <el-form-item :label="`题目：`">
                                        <el-row :gutter="20">
                                            <el-col :span="20">
                                                <div class="grid-content bg-purple"
                                                     v-html="question.questionTitle"></div>
                                                <div class="answer">
                                                    <span>A. {{question.optionA}}</span>
                                                    <span>B. {{question.optionB}}</span>
                                                    <span>C. {{question.optionC}}</span>
                                                    <span>D. {{question.optionD}}</span>
                                                </div>
                                            </el-col>
                                            <el-col :span="1">
                                                <div class="grid-content bg-purple">
                                                    <el-button type="text" @click="deleteQuestion(index)">删除
                                                    </el-button>
                                                </div>
                                            </el-col>
                                        </el-row>
                                    </el-form-item>
                                </div>
                            </div>
                        </el-card>
                    </el-form-item>

                    <el-form-item label="判断题">
                        <el-card class="box-card">
                            <div v-for="(question,index) in form.questionList" :key="index">
                                <div v-if="question.questionType == 3">
                                    <el-form-item :label="`题目${(index+1)}：`">
                                        <el-row :gutter="20">
                                            <el-col :span="20">
                                                <div class="grid-content bg-purple"
                                                     v-html="question.questionTitle"></div>
                                                <div class="answer">
                                                    <span>{{question.optionA}}</span>
                                                    <span>{{question.optionB}}</span>
                                                </div>
                                            </el-col>
                                            <el-col :span="1">
                                                <div class="grid-content bg-purple">
                                                    <el-button type="text" @click="deleteQuestion(index)">删除
                                                    </el-button>
                                                </div>
                                            </el-col>
                                        </el-row>
                                    </el-form-item>
                                </div>
                            </div>
                        </el-card>
                    </el-form-item>

                    <el-form-item label="填空题">
                        <el-card class="box-card">
                            <div v-for="(question,index) in form.questionList" :key="index">
                                <div v-if="question.questionType == 4">
                                    <el-form-item :label="`题目${(index+1)}：`">
                                        <el-row :gutter="20">
                                            <el-col :span="20">
                                                <div class="grid-content bg-purple"
                                                     v-html="question.questionTitle"></div>
                                            </el-col>
                                            <el-col :span="1">
                                                <div class="grid-content bg-purple">
                                                    <el-button type="text" @click="deleteQuestion(index)">删除
                                                    </el-button>
                                                </div>
                                            </el-col>
                                        </el-row>
                                    </el-form-item>
                                </div>
                            </div>
                        </el-card>
                    </el-form-item>

                    <el-form-item label="客观题">
                        <el-card class="box-card">
                            <div v-for="(question,index) in form.questionList" :key="index">
                                <div v-if="question.questionType == 5">
                                    <el-form-item :label="`题目${(index+1)}：`">
                                        <el-row :gutter="20">
                                            <el-col :span="20">
                                                <div class="grid-content bg-purple"
                                                     v-html="question.questionTitle"></div>
                                            </el-col>
                                            <el-col :span="1">
                                                <div class="grid-content bg-purple">
                                                    <el-button type="text" @click="deleteQuestion(index)">删除
                                                    </el-button>
                                                </div>
                                            </el-col>
                                        </el-row>
                                    </el-form-item>
                                </div>
                            </div>
                        </el-card>
                    </el-form-item>

                    <div>
                        <SelectQuestion :question-dialog-visible="questionDialogVisible"
                                        @trans_select="get_select"></SelectQuestion>
                    </div>
                    <el-form-item label="考试类型">
                        <el-select v-model="form.paperType" placeholder="请选择"
                                   @change="changePaperTypeHandle">
                            <el-option v-for="item in paperType" :key="item.id" :label="item.value"
                                       :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="考试时段" v-if="datetimeFlag">
                        <template>
                            <div class="block">
                                <el-date-picker
                                        v-model="datetime"
                                        type="datetimerange"
                                        range-separator="至"
                                        start-placeholder="开始日期"
                                        end-placeholder="结束日期"
                                        @change="changeDatetimeHandle"
                                >
                                </el-date-picker>
                            </div>
                        </template>
                    </el-form-item>
                    <el-form-item label="考试时长（分钟）" label-width="150px">
                        <el-input-number v-model="form.suggestTime" :precision="0" :step="1" :min="1"
                                         :max="1200"
                        ></el-input-number>
                    </el-form-item>
                    <el-form-item label="总分">
                        <el-input-number v-model="form.score" :precision="0" :step="1" :min="1"
                                         :max="500"></el-input-number>
                    </el-form-item>

                    <el-form-item label="test按钮">
                        <el-button type="info" @click="getQuestionCount">question</el-button>
                    </el-form-item>

                    <el-form-item label="考试地点">
                        <el-input v-model="form.address" style="width: 205px;" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="出题老师">
                        <el-select clearable filterable v-model="form.teacherId" placeholder="请选择">
                            <el-option v-for="item in teacher" :key="item.teacherId" :label="item.teacherName"
                                       :value="item.teacherId"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <div class="grid-content bg-purple">
                                <el-form-item label="难度">
                                    <el-rate
                                            v-model="form.difficult"
                                            :texts="texts"
                                            show-text
                                            style="display: inline"
                                    >
                                    </el-rate>
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content bg-purple">
                                <el-form-item label="使用状态">
                                    <el-switch
                                            v-model="form.useStatus"
                                            active-color="#13ce66"
                                            inactive-color="#ff4949"
                                            active-value="1"
                                            inactive-value="0"
                                    >
                                    </el-switch>
                                </el-form-item>
                            </div>
                        </el-col>
                    </el-row>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button size="median" type="primary" @click="save" v-preventReClick>确 定</el-button>
                    <el-button size="median" @click="form = {}">重 置</el-button>

                </div>
            </div>
            <!--编辑器-->
            <el-dialog :visible.sync="dialogVisible" width="50%">
                <div>
                    <vue-editor v-model="content" :editor-toolbar="customToolbar"/>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="editorSave">确 定</el-button>
                    <el-button @click="dialogVisible = false">取 消</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>

    import request from "../utils/request";
    import {serverIp} from "../../public/config";
    import SelectQuestion from "./SelectQuestion"

    export default {
        name: 'EditPaper',
        components: {SelectQuestion,},
        data() {
            return {
                form: {
                    useStatus: "1",
                    score: 1,
                    difficult: 3,
                    createTime: new Date(),
                    suggestTime: 5,
                    questionList: [],
                    makePaperMethod: 2
                },
                questionCountData: [{name: "杨"}],
                radioIndex: 0,
                datetime: {},
                datetimeFlag: false,
                roles: {},
                serverIp: serverIp,
                dialogVisible: false,
                questionDialogVisible: false,
                index: null,
                search: '',
                pageSize: 5,
                pageNum: 1,
                total: 20,
                key:0,
                tableData: [],
                teacher: [],
                course: [],
                content: '',
                formType: '',
                correct: [],
                paperScore:0,
                questionCounts:{},
                correctAnswer: [{value: "A"}, {value: "B"}, {value: "C"}, {value: "D"}],
                paperType: [{id: 1, value: '固定试卷'}, {id: 4, value: '时段试卷'}, {id: 6, value: '上机练习'}],
                makePaperMethod: [{id: 1, value: '固定组卷'}, {id: 2, value: '随机组卷'}],
                texts: ['很简单', '简单', '一般', '难', '很难'],
                rules: {
                    adminId: [
                        {required: true, message: '请输入用戶ID', trigger: 'blur'},
                        {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
                    ]
                },
                customToolbar: [
                    ["bold", "italic", "underline"],
                    [{list: "ordered"}, {list: "bullet"}],
                    ["image", "code-block"]
                ]

            }
        },
        created() {
            this.getTeacher();
            this.getCourse();
            console.log("form:")
            console.log(this.form)
            if (this.$route.params.form) {
                console.log(this.$route.fullPath)
                this.form = this.$route.params.form;
                if (this.form['questionList'] == null) {
                    this.form['questionList'] = [];
                }
            }
            this.changePaperTypeHandle();//是否显示时间段
            this.getQuestionCount();
            console.log("处理后form:")
            console.log(this.form)
        },
        watch: {
            form: { //监听的对象
                deep: true, //深度监听设置为 true
                handler: function (newForm, oldForm) {
                    //重新计算分数
                    this.computePaperScore();

                }
            },
        },
        methods: {
            computePaperScore(){
                let radio = this.form.radioQuestionCount * this.form.radioScore ||0;
                let checkbox = this.form.checkboxQuestionCount * this.form.checkboxScore ||0;
                let judge = this.form.judgeQuestionCount * this.form.judgeScore ||0;
                this.paperScore = radio + checkbox + judge;
            },
            getQuestionCount(){
                if(!this.form['courseId']){
                    this.$message.error("课程名称不能为空")
                    return;
                }
                for (let i = 1; i < 6; i++) {
                    this.questionCounts[i] = 0;
                }
                request.get("/question/find/"+this.form['courseId']).then(res => {
                    const data = res.data;
                    data.forEach(map =>{
                        this.questionCounts[parseInt(map["questionType"])] = map["count"];
                    })
                    console.log("data:",this.questionCounts)
                    this.$forceUpdate() //有问题

                })
            },

            save() {

                console.log("form:", this.form);
                if (this.form.id) { // 更新
                    request.post('/paper/save', this.form).then(res => {
                        console.log("code:", res.code)
                        if (res.code == '200') {
                            this.$message.success("保存成功")
                        } else {
                            this.$message.error("保存失败")
                        }
                    }).catch((err) => {
                        this.$message.error(err);
                    })
                } else { //新增
                    request.post("/paper/save", this.form).then(res => {
                        console.log(res.data)
                        if (res.code == '200') {
                            this.$message.success("添加成功")
                        } else {
                            this.$message.error("添加失败")
                        }
                    }).catch((err) => {
                        this.$message.error("添加失败");
                        this.$message.error(err);
                    })
                }
            },
            getTeacher() {
                //请求教师信息数据
                request.get("/teacher/findAll").then(res => {
                    console.log("res:", res);
                    this.teacher = res.data
                })
            },
            getCourse() {
                //请求课程信息数据
                request.get("/course/findAll").then(res => {
                    console.log("res:", res);
                    this.course = res.data
                })
            },
            focus(formType, formValue) {
                this.formType = formType
                this.content = formValue;
                this.dialogVisible = true;
            },
            editorSave() {
                this.$message.info(this.content);
                this.form[this.formType] = this.content;
                this.content = '';
                this.dialogVisible = false;
            },
            changeDatetimeHandle() {
                if (this.datetime.length == 2) {
                    this.form['limitStartTime'] = this.datetime[0];
                    this.form['limitEndTime'] = this.datetime[1];
                }
            },
            changePaperTypeHandle() {
                console.log(this.form['paperType'])
                if (this.form['paperType'] == 4) {
                    this.datetimeFlag = true;
                } else {
                    this.datetimeFlag = false;
                    delete this.form['limitStartTime'];
                    delete this.form['limitEndTime'];
                }
                this.changeDatetimeHandle();
            },
            changeMakePaperMethodHandle() {
                //组卷方式改变
                //隐藏添加标题按钮
                //隐藏标题内容
            },
            addQuestion() {
                console.log("form:", this.form)
                this.questionDialogVisible = true;
            },
            deleteQuestion(index) {
                //index为题目序号
                this.form.questionList.splice(index, 1);
                this.changeQuestionCount();
            },
            get_select(list) {
                list.forEach(question => {
                    this.form.questionList.push(question)
                })
                this.questionDialogVisible = false;
                console.log("回传list处理后form：", this.form)
                this.changeQuestionCount();
            },
            changeQuestionCount() {
                let groupList = [];
                for (let i = 1; i < 6; i++) {
                    groupList[i] = [];//数组初始化
                }
                for (const question of this.form["questionList"]) {
                    //数据分组
                    if (groupList[question.questionType]) {
                        groupList[question.questionType].push(question);
                    }
                }
                console.log("groupList:", groupList)
                console.log("groupList:", groupList[2])
                this.form['radioQuestionCount'] = groupList[1].length;
                this.form['checkboxQuestionCount'] = groupList[2].length;
                this.form['judgeQuestionCount'] = groupList[3].length;
                this.form['fillQuestionCount'] = groupList[4].length;
                this.form['objectiveQuestionCount'] = groupList[5].length;
            },
        },
    }
</script>
<style>
    .answer span {
        margin-right: 20px;
    }
    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }
    .clearfix:after {
        clear: both
    }
</style>



